/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2023-10-21 08:47:40
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2023-11-04 08:21:06
 * @FilePath: \go2023\admin\serverx\gin.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package serverx

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"sxk.games/m/v2/admin/internal/controller"
)

//加载路由
func LoadRouter() {

	g := gin.Default()

	g.Use(Cors()) //为了解决跨域问题

	g.GET("/sw/hello", controller.Hello)

	g.POST("/sw/user/login", controller.UserLogin)
	g.POST("/sw/user/info", controller.UserInfo)
	g.POST("/sw/user/logout", controller.UserLogout)

	g.POST("/sw/site/create", controller.SiteCreate)
	g.POST("/sw/site/delete", controller.SiteDelete)
	g.POST("/sw/site/update", controller.SiteUpdate)
	g.POST("/sw/site/list", controller.SiteList)

	// 用户
	g.POST("/sw/user/add", controller.AddUser)
	g.POST("/sw/user/get", controller.GetUsers)

	g.Run(":8081")
}

// 解决跨域问题的中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method               //请求方法
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")

			// 这是允许访问所有域
			c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
			// 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			// header的类型
			c.Header("Access-Control-Allow-Headers", "X-Token, Authorization, Content-Length, X-CSRF-Token, Token,session, X_Requested_With, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			// 允许跨域设置,可以返回其他子段
			// 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, FooBar")
			// 缓存请求信息 单位为秒
			c.Header("Access-Control-Max-Age", "172800")
			// 跨域请求是否需要带cookie信息 默认设置为true
			c.Header("Access-Control-Allow-Credentials", "true")
			// 设置返回格式是json
			//c.Set("content-type", "application/json")
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}
